<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\note;

use app\api\controller\Common;
use app\api\model\dao\Circle;
use app\api\model\dao\ContributionRank;
use app\api\model\dao\DashangRecord;
use app\api\model\dao\Note;
use app\api\model\dao\NotePraise;
use app\api\model\dao\NoteStatistics;
use app\api\model\dao\UpRank;
use app\api\model\dao\UserAccount;
use app\api\model\dao\UserCurrency;
use app\api\model\dao\UserFavorite;
use app\api\model\data\note\RecordNoteData;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use think\Exception;
use think\Log;
use think\Validate;

class GetNoteInfo extends PageBase
{

    private $objNote;
    private $objUserAccount;
    private $objDashangRecond;
    private $objRecordNoteData;
    private $objNoteStatistics;
    private $objUpRank;
    private $objCircle;
    private $objNotePraise;
    private $objUserFavorate;
    private $objContributionRank;
    private $objUserCurrency;

    public function __construct()
    {
        parent::__construct();

        $this->objNote = new Note();
        $this->objUserAccount = new UserAccount();
        $this->objDashangRecond = new DashangRecord();
        $this->objRecordNoteData = new RecordNoteData();
        $this->objNoteStatistics = new NoteStatistics();
        $this->objUpRank = new UpRank();
        $this->objCircle = new Circle();
        $this->objNotePraise = new NotePraise();
        $this->objUserFavorate = new UserFavorite();
        $this->objContributionRank = new ContributionRank();
        $this->objUserCurrency = new UserCurrency();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'note_id' => 'require',
        ];
        $msg = [
            'note_id.require' => '帖子ID不能为空',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        $this->checkToken($param);

        $this->user_id = !empty($this->user_id) ? $this->user_id : 0;

        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            Log::error('param error:' . json_encode($param));
            return $this->getRes(Error::ERR_PARAM, $ret);
        }

        // 2、从数据库中获取帖子详情
        $ret = $this->getNoteInfoFromDB($param['note_id']);
        if (false === $ret) {
            Log::error('get note info from db fail. [note_id: ' . $param['note_id'] . ']');
            return $this->getRes(Error::ERR_SYS);
        }

        if (empty($ret)) {
            Log::alert('note info is empty. [note_id: ' . $param['note_id'] . ']');
            return $this->getRes(Error::ERR_NOTE_NOT_EXIST);
        }

        // 3、校验是否被删除
        if (Flag::CONST_NOTE_DELETED == $ret['is_delete']) {
            Log::alert('note is deleted' . json_encode($param));
            return $this->getRes(Error::ERR_NOTE_DELETED);
        }

        // 4、获取圈子信息
        $circle = $this->objCircle->getCircleByid($ret['cir_id']);
        if (false === $circle) {
            Log::error(__METHOD__ . ' get circle info fail. [circle_id: ' . $ret['cir_id'] . ']');
        }

        // 5、获取创建者信息
        $user_account = $this->objUserAccount->getUserAccount(['user_id' => $ret['creator']]);
        if (false === $user_account) {
            Log::error('get user account from db fail. [user_id: ' . $ret['creator'] . ']');
            return $this->getRes(Error::ERR_SYS);
        }
        $user_account = $user_account[0];

        $dashang_recond = $this->objDashangRecond->getDashangRecord(['note_id' => ['=', $param['note_id']]]);
        if (empty($dashang_recond)) {
            $dashang_recond = [];
        }

        $userid = [];
        foreach ($dashang_recond as $val) {
            $userid[] = $val['userid'];
        }

        $dashang_user_info = [];
        if (!empty($userid)) {
            $user_account_dashang = $this->objUserAccount->getUserAccountByUserids($userid);
            if (!empty($user_account_dashang)) {
                $user_account_dashang = $this->modelToArray($user_account_dashang);
                foreach ($user_account_dashang as $val) {
                    $dashang_user_info[] = ['userid' => $val['id'], 'photo' => $val['avatar']];
                }
            }
        }

        $user_integral_ret = $this->objUserCurrency->getCurrencyByUserid($ret['creator'], Flag::CURENCY_TYPE_INTEGRAL);
        if (!empty($user_integral_ret)) {
            $user_integral_ret = \app\library\Common::modelToArray($user_integral_ret);
        } else {
            $user_integral_ret = [];
        }
        $integral = !empty($user_integral_ret['amount']) ? $user_integral_ret['amount'] : 0;
        $user_account['level'] = \app\library\Common::conversionLevel($integral);

        $this->data = $this->composeData($ret, $circle, $user_account, $dashang_user_info);

        // 增加贡献值
        if ($ret['cir_id']) {
            $this->objContributionRank->add($ret['cir_id'], $this->user_id, Flag::$contribution_map['note_view']);
        }

        // PV
        $this->objNoteStatistics->addNoteStatistics(['cir_id' => $ret['cir_id'], 'note_id' => $param['note_id'], 'userid' => $this->user_id]);

        $up_rank_ret = $this->objUpRank->plusUp($user_account['id'], date('Ymd'));
        if (false === $up_rank_ret) {
            Log::error(' add consumer rank fail. [userid:' . $user_account['id'] . '][date:' . date('Ymd') . ']');
        }
        return $this->getRes();
    }

    /**
     * 从数据库中获取帖子详情
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getNoteInfoFromDB($note_id)
    {
        if (!$note_id) {
            return false;
        }
        $arrCond = [
            'id' => ['=', $note_id]
        ];
        $ret = $this->objNote->getNote($arrCond);
        if (false === $ret) {
            return false;
        }
        if (empty($ret)) {
            return [];
        }
        $ret = $ret[0];
        return $ret;
    }

    public function composeData($note_info, $circle, $user_account, $dashang_user_info)
    {
        $data = [];
        $data['creator'] = [
            'nickname' => $user_account['nick_name'],
            'userid' => $note_info['creator'],
            'sex' => $user_account['sex'] ? 'F' : 'M',
            'level' => $user_account['level'],
            'photo' => $user_account['avatar'],
        ];
        $data['note'] = [
            'title' => $note_info['title'],
            'content' => $note_info['content'],
        ];

        if ($note_info['pic']) {
            $data['note']['pic'] = explode(',', urldecode($note_info['pic']));
        }

        if (!empty($circle)) {
            $data['circle']['icon'] = $circle['icon'];
            $data['circle']['name'] = $circle['name'];
        }

        if ($dashang_user_info) {
            $data['reward'] = $dashang_user_info;
        }

        $data['is_praise'] = 0;
        $data['is_fav'] = 0;

        $conds = [
            'note_id' => ['=', $note_info['id']],
            'userid' => ['=', $this->user_id],
        ];
        $retCnt = $this->objNotePraise->getNotePraiseCountByConds($conds);
        if (!empty($retCnt)) {
            $data['is_praise'] = 1;
        }

        $retCnt = $this->objUserFavorate->getFavoriteCountByType(2, $note_info['id'], $this->user_id);
        if (!empty($retCnt)) {
            $data['is_fav'] = 1;
        }

        return $data;
    }
}
